#!/bin/bash

# 鼎红云屏项目 Minikube 部署脚本
# 基于 Docker、Minikube 和 Nginx Ingress

set -e

echo "开始部署鼎红云屏项目到 Minikube..."

# 检查 Minikube 状态
if ! minikube status | grep -q "Running"; then
    echo "启动 Minikube..."
    minikube start --cpus=4 --memory=8192 --disk-size=20g
else
    echo "Minikube 已在运行"
fi

# 启用 Ingress 插件
echo "启用 Ingress 插件..."
minikube addons enable ingress

# 等待 Ingress 控制器就绪
echo "等待 Ingress 控制器就绪..."
kubectl wait --namespace ingress-nginx \
  --for=condition=ready pod \
  --selector=app.kubernetes.io/component=controller \
  --timeout=120s

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 应用 Kubernetes 配置
echo "应用 Kubernetes 配置..."

# 创建命名空间
kubectl apply -f "$SCRIPT_DIR/namespace.yaml"

# 部署数据库
echo "部署 MySQL..."
kubectl apply -f "$SCRIPT_DIR/mysql-deployment.yaml"

# 部署 Redis
echo "部署 Redis..."
kubectl apply -f "$SCRIPT_DIR/redis-deployment.yaml"

# 等待数据库就绪
echo "等待数据库就绪..."
kubectl wait --namespace dinghong-cloud-screen \
  --for=condition=ready pod \
  --selector=app=gva-mysql \
  --timeout=300s

kubectl wait --namespace dinghong-cloud-screen \
  --for=condition=ready pod \
  --selector=app=gva-redis \
  --timeout=300s

# 部署后端服务
echo "部署后端服务..."
kubectl apply -f "$SCRIPT_DIR/configmap-server.yaml"
kubectl apply -f "$SCRIPT_DIR/server-deployment.yaml"

# 部署前端服务
echo "部署前端服务..."
kubectl apply -f "$SCRIPT_DIR/nginx-config.yaml"
kubectl apply -f "$SCRIPT_DIR/web-deployment.yaml"

# 部署 Ingress
echo "部署 Ingress..."
kubectl apply -f "$SCRIPT_DIR/nginx-ingress.yaml"

# 等待所有 Pod 就绪
echo "等待所有服务就绪..."
kubectl wait --namespace dinghong-cloud-screen \
  --for=condition=ready pod \
  --selector=app=gva-server \
  --timeout=300s

kubectl wait --namespace dinghong-cloud-screen \
  --for=condition=ready pod \
  --selector=app=gva-web \
  --timeout=300s

# 获取访问信息
echo "获取访问信息..."
MINIKUBE_IP=$(minikube ip)
echo "Minikube IP: $MINIKUBE_IP"

# 添加本地 hosts 记录
echo "添加本地 hosts 记录..."
if ! grep -q "dinghong-cloud-screen.local" /etc/hosts; then
    echo "$MINIKUBE_IP dinghong-cloud-screen.local" | sudo tee -a /etc/hosts
    echo "已添加 hosts 记录: $MINIKUBE_IP dinghong-cloud-screen.local"
else
    echo "hosts 记录已存在"
fi

# 显示服务状态
echo "显示服务状态..."
kubectl get pods -n dinghong-cloud-screen
kubectl get services -n dinghong-cloud-screen
kubectl get ingress -n dinghong-cloud-screen

echo ""
echo "部署完成！"
echo "访问地址: http://dinghong-cloud-screen.local"
echo "或者: http://$MINIKUBE_IP"
echo ""
echo "如果无法访问，请运行以下命令开启隧道:"
echo "minikube tunnel"
echo ""
echo "查看日志:"
echo "kubectl logs -f deployment/gva-server -n dinghong-cloud-screen"
echo "kubectl logs -f deployment/gva-web -n dinghong-cloud-screen" 